package com.xique.door.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xique.common.core.text.Convert;
import com.xique.common.core.utils.StringUtils;
import com.xique.door.bean.dao.BuildHouseUserDAO;
import com.xique.door.bean.dao.UserHouseCodeDao;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.dto.CardDeviceHouseCodeDTO;
import com.xique.door.bean.dto.UserDeviceHouseCodeDTO;
import com.xique.door.bean.request.buildHouse.UserSelectHouseInfoRequest;
import com.xique.door.bean.request.user.UserSelectRequest;
import com.xique.door.bean.search.build.HouseUserListSearch;
import com.xique.door.bean.vo.user.UserHouseVo;
import com.xique.door.mapper.BuildHouseUserMapper;
import com.xique.door.mapper.BuildHouseUserMapperV1;
import com.xique.door.service.IBuildHouseUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 房屋用户中间表Service业务层处理
 *
 * @author caogq
 * @date 2021-09-09
 */
@Service
public class BuildHouseUserServiceImpl extends ServiceImpl<BuildHouseUserMapperV1, BuildHouseUserV1>
    implements IBuildHouseUserService {
  @Autowired private BuildHouseUserMapper buildHouseUserMapper;

  @Autowired private BuildHouseUserMapperV1 houseUserMapperV1;

  /**
   * 查询房屋用户中间表
   *
   * @param id 房屋用户中间表ID
   * @return 房屋用户中间表
   */
  @Override
  public BuildHouseUser selectBuildHouseUserById(Long id) {
    return buildHouseUserMapper.selectBuildHouseUserById(id);
  }

  /**
   * 查询房屋用户中间表列表
   *
   * @param buildHouseUser 房屋用户中间表
   * @return 房屋用户中间表
   */
  @Override
  public List<BuildHouseUser> selectBuildHouseUserList(BuildHouseUser buildHouseUser) {
    return buildHouseUserMapper.selectBuildHouseUserList(buildHouseUser);
  }

  /**
   * 新增房屋用户中间表
   *
   * @param buildHouseUser 房屋用户中间表
   * @return 结果
   */
  @Override
  public int insertBuildHouseUser(BuildHouseUser buildHouseUser) {
    return buildHouseUserMapper.insertBuildHouseUser(buildHouseUser);
  }

  /**
   * 修改房屋用户中间表
   *
   * @param buildHouseUser 房屋用户中间表
   * @return 结果
   */
  @Override
  public int updateBuildHouseUser(BuildHouseUser buildHouseUser) {
    return buildHouseUserMapper.updateBuildHouseUser(buildHouseUser);
  }

  /**
   * 删除房屋用户中间表对象
   *
   * @param ids 需要删除的数据ID
   * @return 结果
   */
  @Override
  public int deleteBuildHouseUserByIds(String ids) {
    return buildHouseUserMapper.deleteBuildHouseUserByIds(Convert.toStrArray(ids));
  }

  /**
   * 删除房屋用户中间表信息
   *
   * @param id 房屋用户中间表ID
   * @return 结果
   */
  @Override
  public int deleteBuildHouseUserById(Long id) {
    return buildHouseUserMapper.deleteBuildHouseUserById(id);
  }

  @Override
  public List<BuildHouseUserDAO> selectBuildHouseUserByUserIdAndHouseId(Long userId, Long houseId) {
    return buildHouseUserMapper.selectBuildHouseUserByUserIdAndHouseId(userId, houseId);
  }

  @Override
  public int checkUserHouseInBuilding(Long userId, Long buildingId) {
    return buildHouseUserMapper.checkUserHouseInBuilding(userId, buildingId);
  }

  @Override
  public int checkUserHouseInArea(Long userId, Long areaId) {
    return buildHouseUserMapper.checkUserHouseInArea(userId, areaId);
  }

  /**
   * @param userId
   * @description: 查询一个用户的房号
   * @author caogq
   * @date: 2021/11/13 14:44 @Param
   */
  @Override
  public String selectFreeviewHouseCodeByUserId(String userId) {
    List<String> codes = buildHouseUserMapper.selectHouseCodeByUserId(userId);
    if (codes.size() == 1) {
      return codes.get(0).substring(codes.get(0).length() - 4);
    }
    List<String> newCodes = new ArrayList<>();
    for (String code : codes) {
      newCodes.add(code.substring(code.length() - 4));
    }
    return StringUtils.join(newCodes, ",");
  }

  @Override
  public String selectFreeviewHouseCodeByUserIdV1(String userId, List<Long> buildingIds) {
    List<String> codes = buildHouseUserMapper.selectHouseCodeByUserIdV1(userId, buildingIds);
    if (codes.size() == 1) {
      return codes.get(0).substring(codes.get(0).length() - 4);
    }
    List<String> newCodes = new ArrayList<>();
    for (String code : codes) {
      newCodes.add(code.substring(code.length() - 4));
    }
    return StringUtils.join(newCodes, ",");
  }

  /**
   * @param userIds
   * @description: 批量查询用户的房号
   * @author caogq
   * @date: 2021/11/13 14:44 @Param
   */
  @Override
  public Map<String, Object> batchSelectFreeviewHouseCodeByUserIds(List<String> userIds) {
    Map<String, Object> returnMap = new HashMap<>();
    List<UserHouseCodeDao> usercodes = buildHouseUserMapper.batchSelectHouseCodeByUserIds(userIds);
    for (UserHouseCodeDao usercode : usercodes) {
      String code = "";
      List<String> codes = usercode.getCodes();
      if (codes.size() == 1) {
        code = codes.get(0).substring(codes.get(0).length() - 4);
      } else {
        List<String> newCodes = new ArrayList<>();
        for (String item : codes) {
          newCodes.add(item.substring(item.length() - 4));
        }
        code = StringUtils.join(newCodes, ",");
      }

      returnMap.put(String.valueOf(usercode.getUserId()), code);
    }
    return returnMap;
  }

  /**
   * @param
   * @description: 查询一个用户的房号
   * @author caogq
   * @date: 2021/11/13 14:44 @Param
   */
  @Override
  @Deprecated
  public String selectHqFloorCodeByUser(User user) {
    if ("5".equals(user.getType()) || "6".equals(user.getType())) {
      // 保洁全权限
      return "8,40";
    }
    List<String> codes = buildHouseUserMapper.selectHouseCodeByUserId(String.valueOf(user.getId()));
    if (codes.isEmpty()) {
      return "";
    }
    if (codes.size() == 1) {
      // 单楼层
      return codes.get(0).substring(codes.get(0).length() - 4, codes.get(0).length() - 2);
    }
    List<String> newCodes = new ArrayList<>();
    for (String code : codes) {
      newCodes.add(code.substring(code.length() - 4, code.length() - 2));
    }
    // 多楼层
    return 8 + "," + codes.size() + "," + StringUtils.join(newCodes, "/");
  }

  /**
   * @param
   * @description: 批量查询用户的房号
   * @author caogq
   * @date: 2021/11/13 14:44 @Param
   */
  @Override
  public Map<String, Object> batchSelectHqFloorCodeByUsers(List<User> users) {
    Map<String, Object> returnMap = new HashMap<>();
    List<String> userIds =
        users.stream().map(e -> String.valueOf(e.getId())).collect(Collectors.toList());
    List<UserHouseCodeDao> usercodes = buildHouseUserMapper.batchSelectHouseCodeByUserIds(userIds);
    for (User user : users) {
      if ("5".equals(user.getType()) || "6".equals(user.getType())) {
        // 保洁全权限
        returnMap.put(String.valueOf(user.getId()), "8,40");
        continue;
      }
      UserHouseCodeDao usercode =
          usercodes.stream().filter(e -> e.getUserId().equals(user.getId())).findAny().orElse(null);
      if (usercode == null) {
        returnMap.put(String.valueOf(user.getId()), "");
        continue;
      }
      String code = "";
      List<String> codes = usercode.getCodes();
      if (codes.size() == 1) {
        // 单楼层
        code = codes.get(0).substring(codes.get(0).length() - 4, codes.get(0).length() - 2);
      } else {
        List<String> newCodes = new ArrayList<>();
        for (String item : codes) {
          newCodes.add(item.substring(item.length() - 4, item.length() - 2));
        }
        // 多楼层，8：保持时间，size：楼层数量 code：具体楼层用/分割
        code = 8 + "," + codes.size() + "," + StringUtils.join(newCodes, "/");
      }

      returnMap.put(String.valueOf(user.getId()), code);
    }
    return returnMap;
  }

  /**
   * @param
   * @description: 批量查询用户的房号
   * @author caogq
   * @date: 2021/11/13 14:44
   */
  @Override
  public Map<String, Object> batchSelectHqFloorCodeByCards(List<DCard> dCards) {
    Map<String, Object> returnMap = new HashMap<>();
    List<String> userIds =
        dCards.stream().map(e -> String.valueOf(e.getUserId())).collect(Collectors.toList());
    List<UserHouseCodeDao> usercodes = buildHouseUserMapper.batchSelectHouseCodeByUserIds(userIds);
    for (DCard dCard : dCards) {
      if ("5".equals(dCard.getCardType()) || "6".equals(dCard.getCardType())) {
        // 保洁全权限
        returnMap.put(String.valueOf(dCard.getId()), "8,40");
        continue;
      }
      UserHouseCodeDao usercode =
          usercodes.stream()
              .filter(e -> e.getUserId().equals(dCard.getUserId()))
              .findAny()
              .orElse(null);
      if (usercode == null) {
        returnMap.put(String.valueOf(dCard.getId()), "");
        continue;
      }
      List<String> codes = usercode.getCodes();
      String code = "";
      if (codes.size() == 1) {
        // 单楼层
        code = codes.get(0).substring(codes.get(0).length() - 4, codes.get(0).length() - 2);
      } else {
        List<String> newCodes = new ArrayList<>();
        for (String item : codes) {
          newCodes.add(item.substring(item.length() - 4, item.length() - 2));
        }
        // 多楼层，8：保持时间，size：楼层数量 code：具体楼层用/分割
        code = 8 + "," + codes.size() + "," + StringUtils.join(newCodes, "/");
      }
      returnMap.put(String.valueOf(dCard.getId()), code);
    }
    return returnMap;
  }

  /**
   * @param
   * @description: 查询一个用户的房号
   * @author caogq
   * @date: 2021/11/13 14:44 @Param
   */
  @Override
  public String selectHqFloorCodeByCard(DCard dCard) {
    if ("5".equals(dCard.getCardType()) || "6".equals(dCard.getCardType())) {
      // 保洁全权限
      return "8,40";
    }
    List<String> codes =
        buildHouseUserMapper.selectHouseCodeByUserId(String.valueOf(dCard.getUserId()));
    if (codes.isEmpty()) {
      return "";
    }
    if (codes.size() == 1) {
      // 单楼层
      return codes.get(0).substring(codes.get(0).length() - 4, codes.get(0).length() - 2);
    }
    List<String> newCodes = new ArrayList<>();
    for (String code : codes) {
      newCodes.add(code.substring(code.length() - 4, code.length() - 2));
    }
    // 多楼层
    return 8 + "," + codes.size() + "," + StringUtils.join(newCodes, "/");
  }

  /**
   * @param
   * @description: 批量查询用户的房号
   * @author caogq
   * @date: 2021/11/13 14:44 @Param
   */
  @Override
  public Map<String, Object> batchSelectFreeviewHouseCodeByCustomerIds(List<String> customerIds) {
    Map<String, Object> returnMap = new HashMap<>();
    List<UserHouseCodeDao> usercodes =
        buildHouseUserMapper.batchSelectHouseCodeByUserIds(customerIds);
    for (UserHouseCodeDao usercode : usercodes) {
      String code = "";
      List<String> codes = usercode.getCodes();
      if (codes.size() == 1) {
        code = codes.get(0).substring(codes.get(0).length() - 4);
      } else {
        List<String> newCodes = new ArrayList<>();
        for (String item : codes) {
          newCodes.add(item.substring(item.length() - 4));
        }
        code = StringUtils.join(newCodes, ",");
      }

      returnMap.put(String.valueOf(usercode.getUserId()), code);
    }
    return returnMap;
  }

  /**
   * @description: 查询没有绑定的房屋
   * @author caogq
   * @date: 2022/1/27 13:41
   */
  @Override
  public List<BuildHouse> selectUnBindHouseList(UserSelectRequest request) {
    List<BuildHouse> buildHouses = buildHouseUserMapper.selectUnBindHouseList(request);
    return buildHouses;
  }

  @Override
  public List<BuildHouseUser> selectUserHouseInfo(List<Long> userIds) {
    return buildHouseUserMapper.selectUserHouseInfo(userIds);
  }
  /**
   * @param request
   * @description:
   * @author caogq
   * @date: 2022/2/24 15:34 @Param
   */
  @Override
  public List<UserHouseVo> selectHouseBuildingAreaInfo(UserSelectHouseInfoRequest request) {
    List<UserHouseVo> houseBuildingAreaDaos =
        buildHouseUserMapper.selectHouseBuildingAreaInfo(request);
    return houseBuildingAreaDaos;
  }

  @Override
  public List<BuildHouseUser> selectHouseUserList(Long houseId) {
    return buildHouseUserMapper.selectHouseUserList(houseId);
  }

  @Override
  public IPage<BuildHouseUserV1> selectHouseUserPageV1(HouseUserListSearch search) {

    QueryWrapper<BuildHouseUserV1> condition = new QueryWrapper<>();
    if (StringUtils.isNotNull(search.getHouseId())) {
      condition.eq("house_id", search.getHouseId());
    }
    Page<BuildHouseUserV1> page = new Page<>();
    if (StringUtils.isNotNull(search.getPageNum()) && StringUtils.isNotNull(search.getPageSize())) {
      page.setCurrent(search.getPageNum());
      page.setSize(search.getPageSize());
    }
    condition.orderByAsc("id");
    return houseUserMapperV1.selectPage(page, condition);
  }

  @Override
  public List<BuildHouseUserV1> selectHouseUserListV1(HouseUserListSearch search) {
    QueryWrapper<BuildHouseUserV1> condition = new QueryWrapper<>();
    if (StringUtils.isNotNull(search.getHouseId())) {
      condition.eq("house_id", search.getHouseId());
    }
    if (CollectionUtils.isNotEmpty(search.getBuildingIds())) {
      condition.in("building_id", search.getBuildingIds());
    }
    if (StringUtils.isNotNull(search.getUserId())) {
      condition.eq("user_id", search.getUserId());
    }
    condition.orderByAsc("id");
    return houseUserMapperV1.selectList(condition);
  }

  @Override
  public List<UserDeviceHouseCodeDTO> selectHouseCodesByUserDevice(
      List<Long> deviceIds, List<Long> userIds) {
    List<UserDeviceHouseCodeDTO> dtos =
        buildHouseUserMapper.selectHouseCodesByUserDevice(deviceIds, userIds);
    return dtos;
  }

  @Override
  public List<CardDeviceHouseCodeDTO> selectHouseCodesByCardDevice(
      List<Long> deviceIds, List<Long> cardIds) {
    List<CardDeviceHouseCodeDTO> dtos =
        buildHouseUserMapper.selectHouseCodesByCardDevice(deviceIds, cardIds);
    return dtos;
  }

  @Override
  public List<CardDeviceHouseCodeDTO> selectHouseCodesByCard(DCard card) {
    List<CardDeviceHouseCodeDTO> dtos = buildHouseUserMapper.selectHouseCodesByCard(card);
    return dtos;
  }

  @Override
  public BuildHouseUserV1 selectBuildHouseUserV1(BuildHouseUserV1 buildHouseUserV1) {
    QueryWrapper<BuildHouseUserV1> condition = new QueryWrapper<>();
    if (StringUtils.isNotNull(buildHouseUserV1.getUserId())) {
      condition.eq("user_id", buildHouseUserV1.getUserId());
    }
    if (StringUtils.isNotNull(buildHouseUserV1.getHouseId())) {
      condition.eq("house_id", buildHouseUserV1.getHouseId());
    }
    if (StringUtils.isNotNull(buildHouseUserV1.getBuildingId())) {
      condition.eq("building_id", buildHouseUserV1.getBuildingId());
    }
    if (StringUtils.isNotNull(buildHouseUserV1.getIdentityType())) {
      condition.eq("identity_type", buildHouseUserV1.getIdentityType());
    }
    return houseUserMapperV1.selectOne(condition);
  }

  @Override
  public int checkHouseUserCount(Long houseId) {
    if (StringUtils.isNull(houseId)) {
      return 100;
    }
    QueryWrapper<BuildHouseUserV1> condition = new QueryWrapper<>();
    condition.eq("house_id", houseId);
    return houseUserMapperV1.selectCount(condition);
  }
}
